package org.jeecg.modules.qyxxora.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.jeecg.modules.qyxx.config.AreaConfigProperties;
import org.jeecg.modules.qyxxora.entity.InterviewData;
import org.jeecg.modules.qyxxora.entity.dto.InterviewDataDto;
import org.jeecg.modules.qyxxora.service.IInterviewDataService;
import org.jeecg.modules.qyxxora.util.ExcelUtils;
import org.jeecg.modules.qyxxora.vo.*;
import org.jeecg.modules.qyxx.mapper.StatisticsMapper;
import org.jeecg.modules.qyxxora.service.IStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.jeecg.modules.qyxxora.entity.dto.StatCommonDto;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author chensherun on 2022/1/13.
 * @version 1.0
 */
@Service
public class StatisticsServiceImpl implements IStatisticsService {

    @Resource
    private StatisticsMapper statisticsMapper;

    @Autowired
    private AreaConfigProperties areaConfigProperties;

    @Value("${statistic.balance.unit:万元}")
    private String balanceUnit;

    @Value("${statistic.balance.dividend:1}")
    private BigDecimal dividend;

    @Override
    public String selectScyszbjcMaxSsny(String year) {
        return statisticsMapper.selectScyszbjcMaxSsny(year);
    }

    @Override
    public List<StatCityWarningVo> selectCityWarning(String ssny) {
        List<StatCityWarningVo> list = statisticsMapper.selectCityWarning(ssny);
        Map<String, AreaConfigProperties.AreaNetCode> areaNetCodeMap = areaConfigProperties.getAreaNetCodeMap();
        for (StatCityWarningVo statCityWarningVo : list) {
            String cityCode = statCityWarningVo.getCityCode();
            AreaConfigProperties.AreaNetCode areaNetCode = areaNetCodeMap.get(cityCode);
            if (areaNetCode != null) {
                statCityWarningVo.setCitySaleNetCode(areaNetCode.getNetCode());
                statCityWarningVo.setName(areaNetCode.getAreaName());
                statCityWarningVo.setValue(statCityWarningVo.getBalance());
            }
            //预警率
            if (statCityWarningVo.getBalance() != null && statCityWarningVo.getBalance().compareTo(BigDecimal.ZERO) > 0) {
                //statCityWarningVo.setWarningRate(new BigDecimal((float)statCityWarningVo.getWarningCusCount() / statCityWarningVo.getAuthCusCount() * 100).setScale(2, BigDecimal.ROUND_HALF_UP));
                statCityWarningVo.setWarningRate(statCityWarningVo.getWarningBalance().multiply(new BigDecimal(100)).divide(statCityWarningVo.getBalance(), 2, BigDecimal.ROUND_HALF_UP));
            } else {
                statCityWarningVo.setWarningRate(BigDecimal.ZERO);
            }
            //预警响应率
            if (statCityWarningVo.getWarningCount() != null && statCityWarningVo.getWarningCount() != 0) {
                statCityWarningVo.setResponseRate(new BigDecimal((float) statCityWarningVo.getWarningResponseCount() / statCityWarningVo.getWarningCount() * 100).setScale(2, BigDecimal.ROUND_HALF_UP));
            } else {
                statCityWarningVo.setResponseRate(BigDecimal.ZERO);
            }
            //单位转换
            statCityWarningVo.setBalance(statCityWarningVo.getBalance().divide(dividend, 2, BigDecimal.ROUND_HALF_UP));
            statCityWarningVo.setWarningBalance(statCityWarningVo.getWarningBalance().divide(dividend, 2, BigDecimal.ROUND_HALF_UP));
        }
        return list;
    }

    @Override
    public List<StatChildOrgWarningVo> selectChildOrgWarning(String ssny, String saleNetCode) {
        List<StatChildOrgWarningVo> statChildOrgWarningList = statisticsMapper.selectChildOrgWarning(ssny, saleNetCode);
        statChildOrgWarningList.forEach(vo -> {
            //预警率
            if (vo.getBalance() != null && vo.getBalance().compareTo(BigDecimal.ZERO) > 0) {
                vo.setWarningRate(vo.getWarningBalance().multiply(new BigDecimal(100)).divide(vo.getBalance(), 2, BigDecimal.ROUND_HALF_UP));
            } else {
                vo.setWarningRate(BigDecimal.ZERO);
            }
            //预警响应率
            if (vo.getWarningCount() != null && vo.getWarningCount() != 0) {
                vo.setResponseRate(new BigDecimal((float) vo.getWarningResponseCount() / vo.getWarningCount() * 100).setScale(2, BigDecimal.ROUND_HALF_UP));
            } else {
                vo.setResponseRate(BigDecimal.ZERO);
            }

            //单位转换
            vo.setBalance(vo.getBalance().divide(dividend, 2, BigDecimal.ROUND_HALF_UP));
            vo.setWarningBalance(vo.getWarningBalance().divide(dividend, 2, BigDecimal.ROUND_HALF_UP));
        });
        return statChildOrgWarningList;
    }

    @Override
    public StatWaringSituation selectStatWaringSituation(String ssny, String saleNetCode) {
        StatWaringSituation statWaringSituation = statisticsMapper.selectStatWaringSituation(ssny, saleNetCode);
        if (statWaringSituation != null) {
            statWaringSituation.setSsny(ssny);
            BigDecimal balance = statWaringSituation.getBalance();
            BigDecimal oneHundred = new BigDecimal(100);
            //正常余额
            statWaringSituation.setBalanceNormal(balance.subtract(statWaringSituation.getBalanceL1()).subtract(statWaringSituation.getBalanceL2()).subtract(statWaringSituation.getBalanceL3()));
            if (balance != null && balance.compareTo(new BigDecimal(0)) > 0) {
                statWaringSituation.setBalanceL1Rate(statWaringSituation.getBalanceL1().multiply(oneHundred).divide(balance, 2, BigDecimal.ROUND_HALF_UP));
                statWaringSituation.setBalanceL2Rate(statWaringSituation.getBalanceL2().multiply(oneHundred).divide(balance, 2, BigDecimal.ROUND_HALF_UP));
                statWaringSituation.setBalanceL3Rate(statWaringSituation.getBalanceL3().multiply(oneHundred).divide(balance, 2, BigDecimal.ROUND_HALF_UP));
                //正常余额占比
                statWaringSituation.setBalanceNormalRate(statWaringSituation.getBalanceNormal().multiply(oneHundred).divide(balance, 2, BigDecimal.ROUND_HALF_UP));
            } else {
                statWaringSituation.setBalanceL1Rate(BigDecimal.ZERO);
                statWaringSituation.setBalanceL2Rate(BigDecimal.ZERO);
                statWaringSituation.setBalanceL3Rate(BigDecimal.ZERO);
                statWaringSituation.setBalanceNormalRate(BigDecimal.ZERO);
            }
            //预警率
            if (statWaringSituation.getBalance() != null && statWaringSituation.getBalance().compareTo(BigDecimal.ZERO) > 0) {
                statWaringSituation.setWarningRate(statWaringSituation.getBalanceL1()
                        .add(statWaringSituation.getBalanceL2())
                        .add(statWaringSituation.getBalanceL3())
                        .multiply(new BigDecimal(100))
                        .divide(statWaringSituation.getBalance(), 2, BigDecimal.ROUND_HALF_UP));
            } else {
                statWaringSituation.setWarningRate(BigDecimal.ZERO);
            }
            //单位转换
            statWaringSituation.setBalance(statWaringSituation.getBalance().divide(dividend, 2, BigDecimal.ROUND_HALF_UP));
            statWaringSituation.setBalanceNormal(statWaringSituation.getBalanceNormal().divide(dividend, 2, BigDecimal.ROUND_HALF_UP));
            statWaringSituation.setBalanceL1(statWaringSituation.getBalanceL1().divide(dividend, 2, BigDecimal.ROUND_HALF_UP));
            statWaringSituation.setBalanceL2(statWaringSituation.getBalanceL2().divide(dividend, 2, BigDecimal.ROUND_HALF_UP));
            statWaringSituation.setBalanceL3(statWaringSituation.getBalanceL3().divide(dividend, 2, BigDecimal.ROUND_HALF_UP));
        }
        return statWaringSituation;
    }

    @Override
    public StatResponseSituation selectStatWarningResponseSituation(String ssny, String saleNetCode) {
        StatResponseSituation statResponseSituation = statisticsMapper.selectStatWarningResponseSituation(ssny, saleNetCode);
        if (statResponseSituation.getWarningCount() != null && statResponseSituation.getWarningCount() > 0) {
            statResponseSituation.setResponseRate(new BigDecimal((float) (statResponseSituation.getCheckingCount() + statResponseSituation.getCheckedCount()) / statResponseSituation.getWarningCount() * 100).setScale(2, BigDecimal.ROUND_HALF_UP));
        } else {
            statResponseSituation.setResponseRate(BigDecimal.ZERO);
        }
        return statResponseSituation;
    }

    @Override
    public List<StatIndexWarningResponseVo> selectStatIndexWarningResponse(String ssny, String saleNetCode, String zblxItemVaues) {
        List<StatIndexWarningResponseVo> statIndexWarningResponses = statisticsMapper.selectStatIndexWarningResponse(ssny, saleNetCode, zblxItemVaues);
        //计算响应率
        statIndexWarningResponses.forEach(vo -> {
            if (vo.getWarningCount() != null && vo.getWarningCount() > 0) {
                vo.setResponseRate(new BigDecimal((float) (vo.getCheckingCount() + vo.getCheckedCount()) / vo.getWarningCount() * 100).setScale(2, BigDecimal.ROUND_HALF_UP));
            } else {
                vo.setResponseRate(BigDecimal.ZERO);
            }
        });
        return statIndexWarningResponses;
    }

    @Override
    public List<ResponseConditionVo> selectAreaResponse(String ssny) {
        return statisticsMapper.selectAreaResponse(ssny);
    }

    @Override
    public List<WarningConditionVo> selectAreaWarning(String ssny) {
        return statisticsMapper.selectAreaWarning(ssny);
    }

    @Override
    public List<WarningConditionVo> selectDistrictWarning(List<String> ids, String ssny) {
        List<WarningConditionVo> warningConditionVos = statisticsMapper.selectDistrictWarning(ids, ssny);
        warningConditionVos.forEach(vo -> {
            //预警率
            if (vo.getTotal().compareTo(BigDecimal.ZERO) == 0) {
                vo.setWarningRate(BigDecimal.ZERO);
            } else {
                vo.setWarningRate(vo.getWarningRemaining().multiply(new BigDecimal(100)).divide(vo.getTotal(), 2, BigDecimal.ROUND_HALF_UP));
            }
        });
        return warningConditionVos;
    }

    @Override
    public List<ResponseConditionVo> selectDistrictResponse(List<String> ids, String ssny) {
        return statisticsMapper.selectDistrictResponse(ids, ssny);
    }

    @Override
    public List<String> selectIdByCode(String code) {
        List<String> list = new ArrayList<>();
        if ("A04".equals(code)) {
            String id = statisticsMapper.selectIdByCode(code);
            list = statisticsMapper.selectIdsByParentId(id);
        } else {
            String id = statisticsMapper.selectIdByCode(code);
            list.add(id);
        }
        return list;
    }

    @Override
    public List<StatWarningByOrgTypeVo> selectWarningByOrgType(String ssny, String saleNetCode, String dictItems) {
        return statisticsMapper.selectWarningByOrgType(ssny, saleNetCode, dictItems);
    }

    @Override
    public List<StatResponseByOrgTypeVo> selectResponseByOrgType(String ssny, String saleNetCode, String dictItems) {
        return statisticsMapper.selectResponseByOrgType(ssny, saleNetCode, dictItems);
    }

    @Override
    public List<WarningByIndustryTypeVo> getWarningByIndustryType(StatCommonDto statCommonDto) {
        List<WarningByIndustryTypeVo> warningByIndustryTypeVos = statisticsMapper.getWarningByIndustryType(statCommonDto);
        warningByIndustryTypeVos.forEach(vo -> {
            //预警率
            if (vo.getTotal().compareTo(BigDecimal.ZERO) == 0) {
                vo.setWarningRate(BigDecimal.ZERO);
            } else {
                vo.setWarningRate(vo.getWarningRemaining().multiply(new BigDecimal(100)).divide(vo.getTotal(), 2, BigDecimal.ROUND_HALF_UP));
            }
        });
        return warningByIndustryTypeVos;
    }

    @Override
    public List<ResponseByIndustryTypeVo> getResponseByIndustryType(StatCommonDto statCommonDto) {
        return statisticsMapper.getResponseByIndustryType(statCommonDto);
    }

    @Override
    public List<StatWarningTrendChartVo> selectWarningTrendChart(String ssnyq, String ssnyz, String saleNetCode) {
        List<StatWarningTrendChartVo> statWarningTrendChartVos = statisticsMapper.selectWarningTrendChart(ssnyq, ssnyz, saleNetCode);
        statWarningTrendChartVos.forEach(vo -> {
            //合并预警客户数，预警余额， 客户预警率
            vo.setWarningCusCount(vo.getWarningCusCountL1() + vo.getWarningCusCountL2() + vo.getWarningCusCountL3());
            vo.setWarningBalance(vo.getBalanceL1().add(vo.getBalanceL2()).add(vo.getBalanceL3()));
            if (vo.getBalance() != null && vo.getBalance().compareTo(BigDecimal.ZERO) > 0) {
                vo.setWarningRate(vo.getWarningBalance().multiply(new BigDecimal(100)).divide(vo.getBalance(), 2, BigDecimal.ROUND_HALF_UP));
            } else {
                vo.setWarningRate(BigDecimal.ZERO);
            }

            //单位转换
            vo.setBalance(vo.getBalance().divide(dividend, 2, BigDecimal.ROUND_HALF_UP));
            vo.setWarningBalance(vo.getWarningBalance().divide(dividend, 2, BigDecimal.ROUND_HALF_UP));
            vo.setBalanceL1(vo.getBalanceL1().divide(dividend, 2, BigDecimal.ROUND_HALF_UP));
            vo.setBalanceL2(vo.getBalanceL2().divide(dividend, 2, BigDecimal.ROUND_HALF_UP));
            vo.setBalanceL3(vo.getBalanceL3().divide(dividend, 2, BigDecimal.ROUND_HALF_UP));
        });
        return statWarningTrendChartVos;
    }

    @Override
    public List<StatResponseTrendChartVo> selectResponseTrendChart(String ssnyq, String ssnyz, String saleNetCode) {
        List<StatResponseTrendChartVo> list = statisticsMapper.selectResponseTrendChart(ssnyq, ssnyz, saleNetCode);
        list.forEach(vo -> {
            if (vo.getWarningCount() != null && vo.getWarningCount() > 0) {
                vo.setResponseRate(new BigDecimal((float) (vo.getCheckingCount() + vo.getCheckedCount()) / vo.getWarningCount() * 100).setScale(2, BigDecimal.ROUND_HALF_UP));
            } else {
                vo.setResponseRate(BigDecimal.ZERO);
            }
        });
        return list;
    }

    @Override
    public List<Map<String, Object>> testListParm(String itemValues) {
        return statisticsMapper.testListParm(itemValues);
    }

    @Autowired
    private IInterviewDataService interviewDataService;

    @Override
    public boolean analysisInterviewDataExcle(MultipartFile file, String ssny) {
        boolean flag = true;
        Field[] fields = InterviewDataDto.class.getDeclaredFields();
        List<String> fileNameList = new ArrayList<>();
        for (Field field : fields) {
            field.setAccessible(true);
            fileNameList.add(field.getName());
        }
        String[] fileNames = new String[fileNameList.size()];
        //5.2、创建工作薄
        Workbook workbook = null;
        try {
            InputStream fileInputStream = file.getInputStream();
            //5.2、创建工作薄
            workbook = WorkbookFactory.create(fileInputStream);
            List<JSONObject> cgInterviewList = ExcelUtils.importExcel(workbook, 0, fileNameList.toArray(fileNames));
            List<JSONObject> zdInterviewList = ExcelUtils.importExcel(workbook, 1, fileNameList.toArray(fileNames));
            if (cgInterviewList != null) {
                saveInterviewData(cgInterviewList, 0, ssny);
            }
            if (zdInterviewList != null) {
                saveInterviewData(zdInterviewList, 1, ssny);
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {

                }
            }
        }
        return flag;
    }

    public void saveInterviewData(List<JSONObject> list, Integer status, String ssny) {
        for (JSONObject jsonObject : list) {
            InterviewDataDto interviewDataDto = jsonObject.toJavaObject(InterviewDataDto.class);
            String cityName = interviewDataDto.getCityName();
            if ("小计".equals(cityName)) {
                continue;
            }
            String cityCode = areaConfigProperties.getAreaCityCode(cityName);
            BigDecimal riskUserNum = interviewDataDto.getRiskUserNum();
            BigDecimal interviewUserNum = interviewDataDto.getInterviewUserNum();
            BigDecimal interviewRate = interviewDataDto.getInterviewRate();
            if (interviewRate == null && riskUserNum != null && riskUserNum.compareTo(BigDecimal.ZERO) != 0 && interviewUserNum != null) {
                interviewRate = interviewUserNum.divide(riskUserNum, 2, BigDecimal.ROUND_HALF_UP);
            } else if (interviewRate != null) {
                interviewRate = interviewRate.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
            }
            InterviewData interviewData = new InterviewData();
            interviewData.setAreaName(interviewDataDto.getArea());
            interviewData.setCityName(cityName);
            interviewData.setCityCode(cityCode);
            interviewData.setRiskUserNum(riskUserNum);
            interviewData.setInterviewUserNum(interviewUserNum);
            interviewData.setInterviewRate(interviewRate);
            interviewData.setSsny(ssny);
            interviewData.setStatus(status);
            interviewDataService.saveOrUpdateByMultiId(interviewData);
        }
    }

    public static void main(String[] args) {
        BigDecimal bigDecimal = new BigDecimal((float) (new Integer(0) + new Integer(0)) / 10 * 100).setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println(bigDecimal);
    }
}
